package com.imesne.office.excel.read;

import com.imesne.office.excel.model.ExcelRange;
import com.imesne.office.excel.model.ExcelRow;
import com.imesne.office.excel.model.ExcelSheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.util.List;

/**
 * Created by liyd on 17/7/3.
 */
public class ExcelSheetReaderImpl extends AbstractConfigReader implements ExcelSheetReader {

    public boolean isSupportRead(Workbook workbook, Sheet sheet, int sheetIndex) {
        List<ExcelRange> ranges = this.getExcelReaderConfig().getExcelRanges();
        if (ranges == null || ranges.isEmpty()) {
            return true;
        }
        for (ExcelRange range : ranges) {
            if (range.getSheetNum() > 0 && range.getSheetNum() - 1 == sheetIndex) {
                return true;
            }
        }
        return false;
    }

    public ExcelSheet readExcelSheet(Workbook workbook, Sheet sheet, int sheetIndex) {

        ExcelSheet excelSheet = new ExcelSheet(sheet.getSheetName());
        excelSheet.setSheet(sheet);
        excelSheet.setSheetNum(sheetIndex + 1);
        ExcelRowReader excelRowReader = this.getExcelReaderConfig().getExcelRowReader();
        int lastRowNum = sheet.getLastRowNum();
        excelSheet.setLastRowNum(lastRowNum);
        for (int i = 0; i <= lastRowNum; i++) {
            Row row = sheet.getRow(i);
            boolean supportRead = excelRowReader.isSupportRead(workbook, sheet, sheetIndex, row, i);
            if (!supportRead) {
                continue;
            }

            ExcelRow excelRow = excelRowReader.readExcelRow(workbook, sheet, sheetIndex, row, i);

            int mode = AbstractExcelReadProcessor.CONTINUE;
            if (this.getExcelReaderConfig().getExcelReadProcessor() != null) {
                mode = this.getExcelReaderConfig().getExcelReadProcessor().processExcelRow(excelRow, row, workbook, sheet, sheetIndex, i);
            }

            if (mode == AbstractExcelReadProcessor.CONTINUE) {
                addRow(excelSheet, excelRow, i);
            } else if (mode == AbstractExcelReadProcessor.STOP_INCLUSIVE) {
                addRow(excelSheet, excelRow, i);
                break;
            } else if (mode == AbstractExcelReadProcessor.STOP_EXCLUSIVE) {
                break;
            }
        }
        return excelSheet;
    }

    private void addRow(ExcelSheet excelSheet, ExcelRow excelRow, int rowIndex) {
        if (rowIndex == 0 && this.getExcelReaderConfig().isFirstRowTitle()) {
            excelSheet.setTitleRow(excelRow);
        } else {
            excelSheet.addRow(excelRow);
        }
    }
}
